<?php
class Exts_Models_Rules extends Exts_Db_Table_Abstract
{
    protected $_name = 'acl_rules';
    protected $_primary = 'id';

    public function saveBatch( $bind, $roleId )
    {
        $this->_removeAllRules($roleId );
        foreach( $bind as $rule ) {
            $row = $this->createRow();
            $row->setFromArray($rule);
            $row->save();
        }

    }

    private function _removeAllRules($roleId )
    {
        $this->delete("role_id='{$roleId}'");
    }

    public function getRulesByUser( $id )
    {

        if( empty( $id )) {
            throw new Exception( 'No se enontro el usuario' );
            return false;
        }

        $rowset = $this->getAdapter()->fetchAll(
            $this->getAdapter()->select()
                ->from( array('ur' => 'acl_users_roles' ), array() )
                ->join( array( 'ar' => 'acl_rules' ), 'ar.role_id = ur.role_id', array('*') )
                ->join( array( 're' => 'acl_resources'), 're.id=ar.resource_id', array('name') )
                ->where('ur.user_id=?', $id )
        );

        return $rowset;
    }

    public function getRulesByRoleId( $id, $query = false )
    {

        if( empty( $id )) {
            throw new Exception( 'No se enontro el rol' );
            return false;
        }
        $stmt = $this->getAdapter()->select()
            ->from( array( 'ar' => 'acl_rules' ), array('*'))
            ->join( array( 're' => 'acl_resources'), 're.id=ar.resource_id', array('name') )
            ->where('ar.role_id=?', $id )
            ->order( 're.name DESC' );

        if( $query == true ) {
            return $query;
        }
        $rowset = $this->getAdapter()->fetchAll( $stmt );
        return $rowset;
    }
}
